<?php

/**
 * This file is part of cdr-bundle.
 * Author: tangzhou
 * Date: 2016/5/4
 * Time: 11:25
 * File: Common.php
 */

namespace Icsoc\EsReportBundle\Common;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Icsoc\CoreBundle\Export\DataType\ArrayType;

/**
 * 报表公用方法
 * Class Common
 * @package Icsoc\EsReportBundle\Common
 */
class Common
{

    /** @var \Symfony\Component\DependencyInjection\Container  */
    private $container;

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * 获取日期
     *
     * @return mixed
     */
    public function getDate()
    {
        $week = date("w");
        $days = $week+7;
        $daye = $week+1;
        $date['startDate'] = date("Y-m-d");
        $date['endDate']   = date("Y-m-d");
        $date['startMonth'] = date("Y-m");
        $date['endMonth']   = date("Y-m");
        $date['day']['today']['start'] = date("Y-m-d");
        $date['day']['today']['end']   = date("Y-m-d");
        $date['day']['yestoday']['start'] = date("Y-m-d", strtotime("-1 day"));
        $date['day']['yestoday']['end']   = date("Y-m-d", strtotime("-1 day"));
        $date['day']['lastweek']['start'] = date("Y-m-d", strtotime("-$days days"));
        $date['day']['lastweek']['end']   = date("Y-m-d", strtotime("-$daye days"));
        $date['day']['thisweek']['start'] = date("Y-m-d", strtotime("-$week days"));
        $date['day']['thisweek']['end']   = date("Y-m-d");
        $date['day']['lastmonth']['start'] = date("Y-m-01", strtotime("last month"));
        $date['day']['lastmonth']['end']   = date("Y-m-t", strtotime("-1 month", time()));
        $date['day']['thismonth']['start'] = date("Y-m-01");
        $date['day']['thismonth']['end']   = date("Y-m-t");
        $date['day']['thisyear']['start'] = date("Y-01-01");
        $date['day']['thisyear']['end']   = date("Y-12-31");
        $date['day']['lastyear']['start'] = date("Y-01-01", strtotime("-1 year"));
        $date['day']['lastyear']['end']   = date("Y-12-31", strtotime("-1 year"));

        $date['month']['today']['start'] = date("Y-m");
        $date['month']['today']['end']   = date("Y-m");
        $date['month']['yestoday']['start'] = date("Y-m", strtotime("-1 day"));
        $date['month']['yestoday']['end']   = date("Y-m", strtotime("-1 day"));
        $date['month']['lastweek']['start'] = date("Y-m", strtotime("-$days days"));
        $date['month']['lastweek']['end']   = date("Y-m", strtotime("-$daye days"));
        $date['month']['thisweek']['start'] = date("Y-m", strtotime("-$week days"));
        $date['month']['thisweek']['end']   = date("Y-m");
        $date['month']['lastmonth']['start'] = date("Y-m", strtotime("last month"));
        $date['month']['lastmonth']['end']   = date("Y-m", strtotime("-1 month", time()));
        $date['month']['thismonth']['start'] = date("Y-m");
        $date['month']['thismonth']['end']   = date("Y-m");
        $date['month']['thisyear']['start'] = date("Y-01");
        $date['month']['thisyear']['end']   = date("Y-12");
        $date['month']['lastyear']['start'] = date("Y-01", strtotime("-1 year"));
        $date['month']['lastyear']['end']   = date("Y-12", strtotime("-1 year"));

        $date['today']['start'] = date("Y-m-d")." 00:00:00";
        $date['today']['end']   = date("Y-m-d")." 23:59:59";
        $date['yestoday']['start'] = date("Y-m-d", strtotime("-1 day"))." 00:00:00";
        $date['yestoday']['end']   = date("Y-m-d", strtotime("-1 day"))." 23:59:59";
        $date['lastweek']['start'] = date("Y-m-d", strtotime("-$days days"))." 00:00:00";
        $date['lastweek']['end']   = date("Y-m-d", strtotime("-$daye days"))." 23:59:59";
        $date['thisweek']['start'] = date("Y-m-d", strtotime("-$week days"))." 00:00:00";
        $date['thisweek']['end']   = date("Y-m-d H:i:s");
        $date['lastmonth']['start'] = date("Y-m-01 H:i:s", mktime(0, 0, 0, date("m")-1, 1, date("Y")));
        $date['lastmonth']['end']   = date("Y-m-t H:i:s", mktime(23, 59, 59, date("m"), 0, date("Y")));
        $date['thismonth']['start'] = date("Y-m-01")." 00:00:00";
        $date['thismonth']['end']   = date("Y-m-t")." 23:59:59";
        $date['thisyear']['start'] = date("Y-01-01")." 00:00:00";
        $date['thisyear']['end']   = date("Y-12-31")." 23:59:59";
        $date['lastyear']['start'] = date("Y-01-01", strtotime("-1 year"))." 00:00:00";
        $date['lastyear']['end']   = date("Y-12-31", strtotime("-1 year"))." 23:59:59";

        return $date;
    }


    /**
     * 导出Excel
     *
     * @param array  $data
     * @param string $title
     * @param array  $link
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function exportExcel(array $data, $title, array $link)
    {
        set_time_limit(0);
        $translator = $this->container->get('translator');

        /** 限制导出条数，导出数据量过大禁止导出 */
        if (count($data) > 25000) {
            $param = array(
                'data'=>array(
                    'msg_detail'=> $translator->trans(
                        'Export export large amount of data in batches, please'
                    ),
                    'type' => 'info',
                ),
            );

            return new RedirectResponse($this->container->get('router')->generate('system_message', $param, 0));
        }

        if (empty($title) || !is_string($title)) {
            $param = array(
                'data'=>array(
                    'msg_detail'=> $translator->trans(
                        'Title is empty or is not string, the type is %type%',
                        array('%type%' => gettype($title))
                    ),
                    'link' => array(
                        $link,
                    ),
                    'type' => 'danger',
                ),
            );

            return new RedirectResponse($this->container->get('router')->generate('system_message', $param, 0));
        }

        $fields = array();
        $titleArray = json_decode($title, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $data = array(
                'data'=>array(
                    'msg_detail'=> $translator->trans(
                        'Parse Json Error: %error%',
                        array('%error%' => json_last_error())
                    ),
                    'link' => array(
                        array(
                            $link,
                        ),
                    ),
                    'type' => 'danger',
                ),
            );

            return new RedirectResponse($this->container->get('router')->generate('system_message', $data, 0));
        }

        $datas = array();
        foreach ($data as $k => $v) {
            foreach ($titleArray as $key => $val) {
                if (!isset($v[$key])) {
                    $v[$key] = '';
                }
                $datas[$k][$key] = $v[$key];
            }
        }

        foreach ($titleArray as $item => $itemText) {
            $fields[$item] = array(
                'name' => $translator->trans($itemText),
                'type' => 'string',
            );
        }

        try {
            $source = new ArrayType($datas, $fields);
            $excel = $this->container->get('icsoc_core.export.excel');
            $excel->export($source);
        } catch (\Exception $e) {
            $data = array(
                'data'=>array(
                    'msg_detail'=> $translator->trans(
                        'Export Excel Error: %error%',
                        array('%error%' => $e->getMessage())
                    ),
                    'link' => array(
                        array(
                            $link,
                        ),
                    ),
                    'type' => 'danger',
                ),
            );

            return new RedirectResponse($this->container->get('router')->generate('system_message', $data, 0));
        }

        return new Response();
    }

    /**
     * 导出CSV
     *
     * @param array  $data
     * @param string $title
     * @param array  $link
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function exportCsv(array $data, $title, array $link)
    {
        set_time_limit(0);
        $translator = $this->container->get('translator');

        /** 限制导出条数，导出数据量过大禁止导出 */
        if (count($data) > 100000) {
            $param = array(
                'data'=>array(
                    'msg_detail'=> $translator->trans(
                        'Export export large amount of data in batches, please'
                    ),
                    'type' => 'info',
                ),
            );

            return new RedirectResponse($this->container->get('router')->generate('system_message', $param, 0));
        }

        if (empty($title) || !is_string($title)) {
            $param = array(
                'data'=>array(
                    'msg_detail'=> $translator->trans(
                        'Title is empty or is not string, the type is %type%',
                        array('%type%' => gettype($title))
                    ),
                    'link' => array(
                        $link,
                    ),
                    'type' => 'danger',
                ),
            );

            return new RedirectResponse($this->container->get('router')->generate('system_message', $param, 0));
        }

        $fields = array();
        $titleArray = json_decode($title, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $data = array(
                'data'=>array(
                    'msg_detail'=> $translator->trans(
                        'Parse Json Error: %error%',
                        array('%error%' => json_last_error())
                    ),
                    'link' => array(
                        array(
                            $link,
                        ),
                    ),
                    'type' => 'danger',
                ),
            );

            return new RedirectResponse($this->container->get('router')->generate('system_message', $data, 0));
        }

        $datas = array();
        foreach ($data as $k => $v) {
            foreach ($titleArray as $key => $val) {
                if (!isset($v[$key])) {
                    $v[$key] = '';
                }
                $datas[$k][$key] = $v[$key];
            }
        }

        foreach ($titleArray as $item => $itemText) {
            $fields[$item] = array(
                'name' => $translator->trans($itemText),
                'type' => 'string',
            );
        }

        try {
            $source = new ArrayType($datas, $fields);
            $excel = $this->container->get('icsoc_core.export.csv');
            $excel->export($source);
        } catch (\Exception $e) {
            $data = array(
                'data'=>array(
                    'msg_detail'=> $translator->trans(
                        'Export Excel Error: %error%',
                        array('%error%' => $e->getMessage())
                    ),
                    'link' => array(
                        array(
                            $link,
                        ),
                    ),
                    'type' => 'danger',
                ),
            );

            return new RedirectResponse($this->container->get('router')->generate('system_message', $data, 0));
        }

        return new Response();
    }
}